<?php
require "auth.php";
require "header.php";
require "lib.dir.php";
?>
<body>

    <div class="editor_head">
        <img src="images/editor_head.png" height="40px" width="100%"><img src="images/editor_logo.png" class="logo" ></img>
    </div>







    <script src="ace/src/ace.js" type="text/javascript" charset="utf-8"></script>
    <script src="ace/src/theme-textmate.js" type="text/javascript" charset="utf-8"></script>
    <script src="ace/src/mode-php.js" type="text/javascript" charset="utf-8"></script>
    <script>
        var my_editor;


        window.onload = function() {
        
            my_editor = ace.edit("prearea1");
            my_editor.setTheme("ace/theme/textmate");
    
            var phpmode = require("ace/mode/php").Mode;
            my_editor.getSession().setMode(new phpmode());
            ace_session=my_editor.getSession();
            my_editor.getSession().on('change', function(){
                $('#txtarea1').val(ace_session.getValue());



            });
        };

        $(document).keyup(function(){
            $('txtarea1').val(ace_session.getValue());
            difference();
        });

    </script>

    <div class="top_container_editor">
        <?php $editor_project_name = $_GET["project"]; ?>
        <div class="editor_project_name" style="display:none;"> <?php echo " Project: " . $editor_project_name . ""; ?> </div>
        <div class="menubar"><input type="image"  class="mac_hover" src="images/save_button.png" height="25px" width="auto" onclick="save_file()" id="save" title="save"/>
            <input type="image"  class="mac_hover" src="images/dbm.png" height="25px" onclick="show_phpmyadmin()" id="padmin" title="database administrator"/>
            <a href="index.php"><img  class="mac_hover"  src="images/project_button.png" height="25px" title="go to projects"/></a>
            <a  href="logout.php"><img  class="mac_hover" src="images/logout_link.png" height="25px" width="auto" title="logout"></a>
        </div>


    </div>











    <!---
    <?php
    //$packages = get_packages($_GET['project']);
    ?>
    --->



    <script type="text/javascript">
	
        //	var str="<html><head></head>\n<body onload='blahblah();'>\nhello world\n</body>\n</html>";
        var radt_project_name='<?php echo $editor_project_name; ?>';
                
        function show_phpmyadmin(){
            window.open("http://<?php echo $_SERVER['SERVER_NAME']; ?>/phpmyadmin","_newtab");
        }
                
        function extract_body_contents(str){

            var obs_pos=str.search('<body'); //open body start
            var obe_pos=0;	 //open body end
            var i=obs_pos;
            for(i=obs_pos;i<str.length;i++){

                if(str[i]=='>'){
                    obe_pos=i;
                    break;
                }

            }


            var cbs_pos=str.search('</body>');
            return str.substring(obe_pos+1,cbs_pos);
        }




        function insert_body_contents(orig,content){

            var obs_pos=orig.search('<body'); //open body start
            var obe_pos=0;	 //open body end
            var i=obs_pos;
            for(i=obs_pos;i<orig.length;i++){

                if(orig[i]=='>'){
                    obe_pos=i;
                    break;
                }

            }
	
            return (orig.substring(0,obe_pos+1)+content+"\n</body></html>");	
	

        }
        //alert(str.substring(obe_pos+1,cbs_pos));
        //document.getElementById('t').value=extract_body_contents(str);
        //alert(insert_body_contents(str,'hahahha'));
    </script>
    <script>
        var id='<?php echo $_SESSION['id']; ?>';
        var files=new Array();
        var differences=new Array();
        var host = "ws://<?php echo $_SERVER['SERVER_NAME']; ?>:5001";
        var socket=null;
        try{
            socket = new WebSocket(host);
                    
            //console.log('WebSocket - status '+socket.readyState);
            socket.onopen    = function(msg){ 
                console.log("Welcome - status "+this.readyState); 
          
                setTimeout('register_client()',1000);
          
          
                socket.onmessage = function(msg){ 
                    //  console.log("Received: "+msg.data); 
                    apply_patches(msg.data);
                };
                //register_client();    
            };
            /*
socket.onclose   = function(msg){ console.log("Disconnected - status "+this.readyState); };
             */
        }
        catch(ex){ console.log(ex); }
        //---------------------------------------------------------------------------------------------
        function txtarea_to_var(){
    
            var i=0;
            var flag=false;
            for(i=0;i<files.length;i++){
        
                if(files[i]['name']==selected_file){
                    flag=true;
                    break;
                }

            }
    
    
    
            if(flag!=true){
                i=files.length;
            }
    
    
            files[i]=new Array();
            files[i]['name']=selected_file;
            var lines;
            var txt=ace_session.getValue();//$('#txtarea1').val();
            txt=txt.replace("\r\n",'\n');
            lines=txt.split('\n');
            files[i]['content']=lines;
             
            //console.log(files);
        }    

        //-----------------------------------------------------------------------------
        function difference(){
    
            var txt=$('#txtarea1').val();
            var lines;
            txt=txt.replace("\r\n",'\n');
            lines=txt.split('\n');
            var new_text=lines;
            var jstr=""; //json string
    
            var i=0;
            var orig;
            var orig_file_index=0;
        
            for(i=0;i<files.length;i++){
            
                if(files[i]['name']==selected_file){
                
                    orig=files[i]['content'];
                    orig_fie_index=i;
                    break;
                }
            
            }
        
            var dif={};    
            var isdif=false;
            if(new_text.length<orig.length){
            
                console.log("Lines deleted from :"+(new_text.length)); 
                isdif=true;
                dif={};    
                dif.type='D';
                dif.file=selected_file;
                dif.by=id;
                dif.diff='';
                dif.pos=new_text.length;
                differences.push(dif);       
        
            }


            for(i=0;i<new_text.length;i++){
        
                if(i>(orig.length-1)){//&& orig[i]==new_text[i]){
                    console.log("new line difference at line :"+i);
                    isdif=true;
                    dif={};
                    dif.type='M';
                    dif.file=selected_file;
                    dif.by=id;
                    dif.diff=new_text[i];
                    dif.pos=i;
                    differences.push(dif);
                }
                else if(orig[i]==new_text[i]){
                    //
                }
                else{
                    isdif=true;
                    dif={};
                    dif.type='M';
                    dif.file=selected_file;
                    dif.by=id;
                    dif.diff=new_text[i];
                    dif.pos=i;
                    differences.push(dif);
                    console.log("diff at line :" + i);
            
                }
            }    
        
        
        
            files[orig_file_index]['content']= new_text;  
        
        
            if(isdif==true){
                /*jstr=JSON.stringify(differences);
        socket.send(jstr);
        differences=new Array();*/
                send_differences();

            }
    
        }    
        //-----------------------------------------------------------------------------
        function apply_patches(data){
                    
            var patches=eval(data);
                    
            console.log(patches);
                    
            var i=0;
            var j=0;
            var len=patches.length;
            for(i=0;i<len;i++){
                        
                if(patches[i].type=='M'){
                            
                    console.log('MOD CMD');
                    for(j=0;j<files.length;j++){
                                
                        if(files[j]['name']==patches[i].file){
                                    
                            patch_line(j,patches[i].pos,patches[i].diff);
                            if(patches[i].file==selected_file){
                                        
                                // $('#txtarea1').val(files[j].content.join("\n"));
                                //editAreaLoader.setValue('txtarea1',files[j].content.join("\n"));
                                        
                                ace_session.setValue(files[j].content.join("\n"));
                            }
                                    
                        }
                    }
                }
                else if(patches[i].type=='D'){
                            
                    console.log('DEL CMD');
                    for(j=0;j<files.length;j++){
                                
                        if(files[j]['name']==patches[i].file){
                                    
                            delete_line(j,patches[i].pos);
                            if(patches[i].file==selected_file){
                                        
                                // $('#txtarea1').val(files[j].content.join("\n"));
                                // editAreaLoader.setValue('txtarea1',files[j].content.join("\n"));
                                ace_session.setValue(files[j].content.join("\n"));
                            }
                                    
                        }
                    }
                }
                        
            }
                    
        }
 
 
 
        //----------------------------------------------------------------------------
        function patch_line(index,pos,patch){
                    
            files[index]['content'][pos]=patch;
                    
                    
        }
                
        //----------------------------------------------------------------------------
        function delete_line(index,pos){
                    
            files[index]['content'].splice(pos,files[index]['content'].length-pos);
                    
        }
 
 
        //-----------------------------------------------------------------------------
        function register_client(){
            console.log('REG CLNT called');
            var dif={};
            dif.type='RC';
            dif.id=id;
            differences.push(dif);
            send_differences();
        }
                
    
        function send_differences(){
            var ix=0;
            var temp_diffs=new Array();
            if(differences.length>5){

                for(ix=0;ix<=5;ix++){
                    temp_diffs.push(differences.shift());
                }

            }
            else{
                
                temp_diffs=differences;
                differences=new Array();
            }
            var s=JSON.stringify(temp_diffs);
            //alert(s.length);
            console.log('SND DIF CALLEd');
            socket.send(s);
            temp_diffs=new Array();
            
            if(differences.length<=0){
                differences=new Array();
                return;
            }
            
            setTimeout(send_differences,50);

        }


        function register_new_file(){
                    
                    
            var dif={};
            dif.type='R';
            dif.file=selected_file;
            differences.push(dif);
            send_differences();
                    
        }
                
        function unregister_file(file_name){
                    
            var dif={};
            dif.type='U';
            dif.file=file_name;
            differences.push(dif);
            send_differences();
                    
        }

        //------------------------------------------------------------------------------------------------
        $(function() {
            $( "#tabs" ).tabs();
        });
   
        function window_min()
        {
            $("#tabs").hide('slide',200);
            $("#maximicon").show();
            $('.tabs_container').css({'left':'30px','width':'95%'});
            $('.editor').css({'left':'30px','width':'95%'});
    
        }
        function win_max()
        {
    
            $("#tabs").show('slide',200);
            $("#maximicon").hide();
            $('.tabs_container').css({'left':'310px','width':'75%'});
            $('.editor').css({'left':'310px','width':'75%'});
        }
    

    
    </script>


    <img src="images/maximicon.png" id="maximicon" style="height:30px;width:30px;position:absolute;top:50px;left:0px;" onclick="win_max()" title="maximise explorer window"/>
    <div id="tabs"  class="explore_tabs_cont">
        <ul>
            <li><a href="#tabs-1">Packs</a></li>
            <li><a href="#tabs-2">Explore</a></li>
            <li style="float:right"><img src="images/minimicon.png" id="maximicon" style="height:30px;width:30px;" onclick="window_min()" title="minimise explorer window"/><li>
        </ul>
        <div id="tabs-1" >
            <input type="text" id="currentdir" value=""><br/>
            <input type="image"   src="images/browse_button.png" height="30px"      title="brwse" onclick="browse_packs()"/>
            <input type="image" src="images/back.png" height="30px" width="auto" title="back" onclick="browse_packs_back()"/><hr/>
            <input type="text" id="pack_name" value="" maxlength="15"><br/>
            <input type="button" value="Add Pack" onclick="create_package()"/>
            <input type="button" value="Add Dir" onclick="create_folder()"/>
            <p>

            <div id="pack_list" class="pack_list">
                <?php
                /* foreach($packages as $package){

                  echo "<span onmousedown='display_pack_files(\"".$package."\")'>P: ".$package."</span><span onclick='delete_package(\"".$package."\")'>delete</span><hr/>";

                  } */
                ?>
            </div>                            <div id="files" style="height:200px;">

            </div>
            <?php
            /* $package_folders=get_package_folders($_GET['project'],"");

              foreach($package_folders as $package_folder){
              echo "<span><img src='images/package_folder.png' height='20px' width='20px'> ".$package_folder."</span>";

              } */
            ?></p>
            <hr/>

        </div>
        <div id="tabs-2">
            <input type="image" src="images/back.png" height="30px" width="auto" onclick="browse_up()"/>
            <input type="text" id="exploredir" value="" style="width: 80%;font-size: 12px;"/>
            <input type="button" value="Refresh" style="font-size:small" onclick="get_explorer_files();" style=""/>
            <input type="button" value="+Upload" style="font-size:small" onclick="upload_file()"/>
            <input type="button" value="+DB" style="font-size:small" onclick="touch_tables()"/> 
            <input type="button" value="+New" style="font-size:small" onclick="touch_new_file()"/>             
            <div id="explr_list">

            </div>

        </div>

    </div>




    <div class="tabs_container" > 
        <table id="tabs_container_table"><td></td></table>
    </div>


    <pre id="prearea1" class="editor"></pre>
    <textarea id="txtarea1" rows=0 cols=0 onkeyup="difference()" style="display:none"></textarea>
    <div id="ckedit" class="editor" ></div> 


    <script type="text/javascript">
	
        var selected_file="";
        function display_pack_files(pack){
            dir=$('#currentdir').val();

            $.get("server/get_pack_files.php",{pack:pack,dir:dir,project:'<?php echo $_GET['project']; ?>'},function(data){
	
                c="<div class='files_div'><span  onmousedown=\"get_file_contents('"+data["controller"]["path"]+"','C:"+data["controller"]["name"]+"')\"><img src=\"images/control.png\" height=\"25px\" width=\"20px\" title=\"Controller\"/> "+data["controller"]["name"]+"</span></div><hr/>";
	
	
                m="<div class='files_div'><span  onmousedown=\"get_file_contents('"+data["model"]["path"]+"','M:"+data["model"]["name"]+"')\"><img src=\"images/model.png\" height=\"25px\" width=\"20px\" title=\"Model\" /> "+data["model"]["name"]+"</span></div><hr/>";
	
                v="<div class='files_div'><span  onmousedown=\"get_file_contents('"+data["view"]["path"]+"','V:"+data["view"]["name"]+"')\"><img src=\"images/view.png\" height=\"25px\" width=\"20px\"  title=\"View\" /> "+data["view"]["name"]+"</span></div><hr/>";
	
                e="<div class='files_div'><span onmousedown=\"get_file_contents('"+data["event_handler"]["path"]+"','E:"+data["event_handler"]["name"]+"')\"><img src=\"images/event.png\" height=\"25px\" width=\"20px\" title=\"Event Handler\" /> "+data["event_handler"]["name"]+"</span></div>";
	
                $('#files').html(c+m+v+e);
	
	
            },'json');


        }
        //---------------------------------------------------
        var original_event_file="";
        var original_event_file_name=new Array();			
        var original_event_file_data=new Array();
var event_checker=1;	
        function get_file_contents(path){
    
        
            $.get("server/get_file_contents.php",{filename:path,id:id},function(data){
                //alert(data);
                check_if_original_event_handler(path,data);
                original_tab_content.push(data);
               
                selected_file=path;
                register_new_file();
                createtab(path,data);
                txtarea_to_var();	
            
	
            });

        }
        //-------------------------------------------------------
        function delete_package(pack)
        {
            
            var del_con=confirm("are you sure?");
            if(del_con==false)
            {
                return;
                    
            }
       
            var cdir=$('#currentdir').val();
            $.get("server/delete_packfiles.php",{packname:pack,project_name:'<?php echo $_GET['project'] ?>',current_dir:cdir},function(data){
                alert(data);
                // $('#pack_list').html('');browse_packs_back()
                browse_packs(); 
           
                //            var i=0;
                //            var str="";
                //            for(i=0;i<data.length;i++){
                //                
                //                str+="<span onmousedown='display_pack_files(\""+data[i]+"\")'>P: "+data[i]+"</span><span onclick='delete_package(\""+data[i]+"\")'>delete</span><hr/>";
                //            }
                //                    $('#pack_list').html(str);    
                //                    $('#files').html("");
                //echo "<span onmousedown='display_pack_files(\"".$package."\")'>P: ".$package."</span><span onclick='delete_package(\"".$package."\")'>delete</span><hr/>";
            
            });





        }

        //-------------------------------------------------------------------------------------------------
        function delete_folder(dri)
        {
            var cdir=$('#currentdir').val();
            $.get("server/delete_folder.php",{dri:dri,project_name:'<?php echo $_GET['project'] ?>',current_dir:cdir},function(data){
                alert(data);
                // $('#pack_list').html('');browse_packs_back()
                browse_packs(); 
            });

        }


        ///----------------------------------------------------------------------------------------------------------
        //----------------------------------------------------------------------------------------------------------
        function touch_tables(){

            $.get("server/sync_db.php",{project_name:'<?php echo $_GET['project'] ?>'},function(data){
                alert(data);
                // $('#pack_list').html('');browse_packs_back()
                get_explorer_files(); 
            });

        }


        //-------------------------------------------------------------------------

        function touch_new_file(){
            var cdir=$('#exploredir').val();
            $.get("server/touch_new_file.php",{project_name:'<?php echo $_GET['project'] ?>',cdir:cdir},function(data){
                alert(data);
                // $('#pack_list').html('');browse_packs_back()
                get_explorer_files(); 
            });

        }

        //----------------------------------------------------------------------------------------------------------

        function check_if_original_event_handler(path,data)
        {
    
   var split_path=path.split("/");
  
    //console.log(split_path[4]);
    
            if(split_path[4]=="event_handler")
                {
                   // alert("yes");
                   
                   for(x in original_event_file_name)
                       {
                           
                       if(path==original_event_file_name[x]) 
                           {
                                event_checker=1; 
                                break;
                               }
                       else
                           {
                     event_checker=0;  
                    
                       }
                       }
                       
                       check_ev(path,data);
                       
                       
                }
    
            // original_event_file=data;
    
    
        }




        //-------------------------------------------------------------------------------------------------------
        //--------------------------------tabs code---------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------------
        var num=0;
        var tab_name=new Array();			//array to store names of the tabs
        var tab_content=new Array();		//aray to store contents of the tabs
        var original_tab_content=new Array();
        var tab="";
        var guitemp=false;  
        //-------------------check if the tabs exist or not----------------------------------
        function createtab(path,data){		//function start

            if(tab_name.length<=0)				//if there are no elements in array
            {
                create_new_tab(path,data);			//create tab
            }
            else
            {
                for(tab in tab_name)				//else loop through the tab
                {

                    if(tab_name[tab]==path)				//if tab_name is equal to path
                    {
                        var cdn=true;						//true
                        break;
                    }
                    else								//else
                    {
                        var cdn=false;						//false
                    }
                }

                if(cdn==true)
                {
                    //alert("tab exist");	
                    show_tab(path);
                    color_tab(path);				//if condition is true then tab exists 
                }
                else
                {
                    create_new_tab(path,data);		//else create new tab
                    color_tab(path);			
                }

            }
        }
        //------------------------create tab----------------------------------------------------------------------------

        function create_new_tab(path,data)									//function start
        {
            selected_file=path;

            var id=path;

            var newtd=document.createElement("td");								//create new  tablebox
            document.getElementById("tabs_container_table").appendChild(newtd);
            newtd.className="tab_td";
            newtd.id="new"+path+"";
       
            tab_disp_name(path);
        
            //add name into box
            // $("#txtarea1").val(data);
            //editAreaLoader.setValue('txtarea1',data);
            ace_session.setValue(data);
        
        
            document.getElementById("closediv"+path+"").onmouseover=function(){document.getElementById("closediv"+path+"").src="images/close_button_over.png";};
        
            document.getElementById("closediv"+path+"").onmouseout=function(){document.getElementById("closediv"+path+"").src="images/close_button.png";};

            document.getElementById("closediv"+path+"").onmousedown=function(){keep_in_textarea();check_save(path);	};
            document.getElementById("name"+path+"").onmousedown=function(){keep_in_textarea();show_tab(path);};
        
        
            tab_name.push(path);												//add the name into an array
            tab_content.push(data);												//add the contents into an array	
       
            showtextarea();
        
            if(check_if_view(path)==true)
            {
            
                button_disabler();
            }

            //color_tab(path);

        }


        //--------------------------------------delete or close tab------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        //--------------------------check if file is saved before delete---------------------------------------------------------------------------------
        function check_save(path)
        {

            for(x in tab_name)
            {
                if(tab_name[x]==path)
                {

                    if(original_tab_content[x]==tab_content[x])
                    {
                        //alert("original:   "+original_tab_content[x]+"  tabcontent:   "+tab_content[x]);
                        show_tab(path);
                        destroy_tab(path);
                    
                        break;
                    }
                    else
                    {
                        //alert("original:   "+original_tab_content[x]+"  tabcontent:   "+tab_content[x]);
                        //alert("edited");
                        show_tab(path);
                        var save_confirm=confirm("do you want to save?");
                        if(save_confirm==true)
                        {
                            save_file(path);
                            destroy_tab(path);
                            break;
                        }
                        else
                        {
                            var destroy_confirm=confirm("are u sure you want to close?");
                    
                            if(destroy_confirm==true)
                            {
                        
                                destroy_tab(path);
                                break;
                            }
                            else
                            {
                        
                            }
            
        
    

                        }
                    }
                }
            }
        }




        //------------tab orientation before delete---------------------
        var prev_tab="";				//stores previous tab path
        var next_tab="";				//stores next tab path
        var n="";
        function destroy_tab(path)								
        {
            var len=tab_name.length;
            len=len-1;
            if(selected_file==path)					
            {
                for(x in tab_name)
                {
                    if(selected_file==tab_name[x])
                    {
                        if(x==len)								//right most tab
                        {
                            //alert("right most tab");
                            n=x;
                            destroy_tab_part(path);
                            prev_tab=tab_name[n-1];
                            for(x in tab_name)
                            {
                                if(prev_tab==tab_name[x])
                                {
                                    show_tab(prev_tab);
                                }
                            }
                        }
                        else
                        {
                            //alert("selected tab");		//selected tab
                            var len=tab_name.length;
                            len=len-1;		
                            //alert(len);
                            for(x=0;x<=len;x++)
                            {
                                if(tab_name[x]==path)
                                {
                                    next_tab=tab_name[x+1];;
                                    //alert(next_tab);
                                    destroy_tab_part(path);
                                }
                            }




                            for(x in tab_name)
                            {
                                if(next_tab==tab_name[x])
                                {

                                    show_tab(next_tab);
                                    //color_tab(next_tab);
                                }
                            }
                        }


                    }
                }
            }

        }

        //---------------deleting the tab-----------------------

        function destroy_tab_part(path)											
        {

            for(x in tab_name)
            {

                if(tab_name[x]==path)
                {
                    document.getElementById("closediv"+path+"").style.visibility="none";
                    var child=document.getElementById("new"+path+"");
                    document.getElementById("tabs_container_table").removeChild(child);


                    tab_name.splice(x,1);
                    tab_content.splice(x,1);
                    original_tab_content.splice(x,1);
                    for(x in original_event_file_name)
                    {
                    if(path==original_event_file_name[x])
                        {
                            original_event_file_name.splice(x,1);
                            original_event_file_data.splice(x,1);
                            break;
                            
                            
                        }
                    }
                    
                    
                    
                }
                if(tab_name.length==0)
                {
                    selected_file="";

                }
                //$("#txtarea1").val("");
                //editAreaLoader.setValue('txtarea1','');
                ace_session.setValue('');
                remove_gui_editor();
                showtextarea();

            }
        }


        //---------------------------------------------------------------------------------------------------------------------------------

        //----------------------show tab if exists or clicked-----------------------------------------------------------------------------

    
        function show_tab(path){
            for(x in tab_name)
            {
            
                if(tab_name[x]==path)
                {
                    selected_file=path;
                    // $('#txtarea1').val(tab_content[x]);
                    // editAreaLoader.setValue('txtarea1',tab_content[x]);
                    ace_session.setValue(tab_content[x]);
                
                
                    showtextarea();
                    color_tab(path);
                }
            
            }
            if(check_if_view(path)==true)
            {
            
                button_disabler();
            }    
        
        
        }
    
        //----------------------keep the typed contents in textarea of the tab---------------------------------------------------------------------------------

        function keep_in_textarea()
        {


            for(x in tab_name)
            {
			
                if(selected_file==tab_name[x])
                {
                    if(check_if_view(tab_name[x])==true)
                    {
                        if(guitemp==true)
                        {    
                                
                            //add gui content into ace editor 
                            
                            tab_content[x]=CKEDITOR.instances.editor1.getData(); 
                            var orig=ace_session.getValue();// editAreaLoader.getValue('txtarea1');//$("#txtarea1").val();
                            // alert(orig);
                            var newcont=tab_content[x];
                            //$("#txtarea1").val(insert_body_contents(orig,newcont));
                    
                            //editAreaLoader.setValue('txtarea1',insert_body_contents(orig,newcont)); 
                            ace_session.setValue(insert_body_contents(orig,newcont));
                        
                            tab_content[x]= ace_session.getValue();
                        
                        
                        }
                        else
                        {
                            tab_content[x]= ace_session.getValue();//editAreaLoader.getValue('txtarea1');//document.getElementById('txtarea1').value;
                        }
                        // tab_content[x]=CKEDITOR.instances.editor1.getData(); 
                        
                    }
                    else
                    {      
                        tab_content[x]=ace_session.getValue();//editAreaLoader.getValue('txtarea1');//document.getElementById('txtarea1').value;
                    }      	
                    //alert(tab_content[x]);
                }
            }

        }
    

        //------------------------------------display name of the tab-----------------------------------------------------------------
        function tab_disp_name(path){

            var type="";
            var tab=new Array();
            tab=path.split('/');

            index=tab.length
            index=index-1;
            i=index-2;
            switch(tab[i])
            {
                case "controller" :type="<table><td><div style=\"width:200px;overflow:hidden;\" id=\"name"+path+"\"><img src=\"images/control.png\" height=\"25px\" width=\"20px\" title=\"Controller\"/>";
                    break;
                
                
                
                
                
                case "model" :type="<table><td><div style=\"width:200px;overflow:hidden;\" id=\"name"+path+"\"><img src=\"images/model.png\" height=\"25px\" width=\"20px\"  title=\"Model\" />";
                    break;
                
                
                
                
                case "view" :type="<table><td>"+
                        "<input onclick=\"text_into_gui();showguieditor();button_disabler();\" type=\"button\" value=\"gui\" id=\"gui"+path+"\"/></td>"+
                        "<td><input onclick=\"gui_into_text();button_disabler();\" type=\"button\" value=\"text\" id=\"text"+path+"\"/></td><td>"+
                        "<div style=\"width:200px;overflow:hidden;\" id=\"name"+path+"\">"+
                        "<img src=\"images/view.png\" height=\"25px\" width=\"20px\" title=\"View\" />";
                
                    open_event_handler();         
                    break;
                
                
                
                
                case "event_handler" :type="<table><td><div style=\"width:200px;overflow:hidden;\" id=\"name"+path+"\"><img src=\"images/event.png\" height=\"25px\" width=\"20px\" title=\"Event Handler\"/>";
                    break;

                }
            

                document.getElementById("new"+path+"").innerHTML=type+""+tab[index]+"</div></td><td><img src=\"images/close_button.png\" class=\"close_tab_button\" id=\"closediv"+path+"\"></td>";



            }

            //----------------------------------------------------------------------------------------------------------------------------------------------------

            //----------------------------change the color of the current tab------------------------------------------------------------------
            function color_tab(path)
            {
                for(x in tab_name)
                {
                    var id=tab_name[x];
                    //id=id.toString();
                    console.log(typeof id);
                    if((typeof id)=='function'){
                   
                    }else{
                        if(tab_name[x]==path)
                        {

                            document.getElementById("new"+id+"").style.backgroundColor="ghostwhite";
                    
                            if(check_if_view(id)==true)
                            {
                                document.getElementById("gui"+id+"").disabled=false;
                                document.getElementById("text"+id+"").disabled=false;
                        
                            }
                    
                        }
               
                        else
                        {

                            // console.log(id);
                            document.getElementById("new"+id+"").style.backgroundColor="gray";
                    
                            if(check_if_view(id)==true)
                            {
                                document.getElementById("gui"+id+"").disabled=true; 
                                document.getElementById("text"+id+"").disabled=true;
                        
                            }
                    
                
                    
                        }
                
               
                    }
                
                
                }
            }

            //---------------------------------------------------------------------------------------------------

            //-------------------------------add the gui editor to view in the textarea or remove the gui editor----------------------------------------------------------
            var editor, html = '';
            //create a gui editor
            add_gui_editor();
            $("#ckedit").hide();
        
            function add_gui_editor()
            {
                if ( editor )
                    return;


                // Create a new editor 
                var config = {};
                editor = CKEDITOR.appendTo( 'ckedit', config, html );
                config.height = 1000;

           

            }



 

       














            /*  //delete gui editor
            function remove_gui_editor()
            {
                if ( !editor )
                    return;
    
                // Retrieve the editor contents. In an Ajax application, this data would be
                // sent to the server or used in any other way.
                //document.getElementById( 'editor_td' ).innerHTML = html = editor.getData();
                $( '#cke_editor1' ).hide();
    
                // Destroy the editor.
                editor.destroy();
                editor = null;
                $('#txtarea1').show();
            }
             */

            function remove_gui_editor()
            {
        
                $("#ckedit").hide();
                CKEDITOR.instances.editor1.setData("");
            }


            function switcher()
            {
    
                if(guitemp==true)
                {
                    showtextarea();  
                }
                else
                {
                    showguieditor();  
                }
    
            }



           
           
           
           
           
           
           
            //hide text area and show gui editor
           
           
           
           
           
           
            function showguieditor()
            {
                guitemp=true;
                //alert(guitemp);
                //$("#txtarea1").hide();
                //editAreaLoader.hide('txtarea1');
                $('#prearea1').hide();
                $("#ckedit").show();
                                                  
            }
                                              
            //hide gui editor and show textarea
            function showtextarea()
            {
            
                guitemp=false;
                // alert(guitemp);
                //document.getElementById("editor_td").onchange=function(){addintotextarea();};
                // $("#txtarea1").show();
                //editAreaLoader.show('txtarea1');
                $('#prearea1').show();
                $("#ckedit").hide();
            }
                                              
                                              
            function text_into_gui()
            {
                                                  
                for(x in tab_name)
                {
                    if(selected_file==tab_name[x])
                    {     
                        tab_content[x]= ace_session.getValue();//editAreaLoader.getValue('txtarea1');//$("#txtarea1").val();
                        var guitext=extract_body_contents( tab_content[x]);
                        CKEDITOR.instances.editor1.setData(guitext);
                        //alert("into gui"+tab_content[x]);            
                    }
                   
                }
                                                  
            }   
    
            function gui_into_text()
            {
        
                for(x in tab_name)
                {
            
                    if(tab_name[x]==selected_file)
                    {
                           
                        tab_content[x]=CKEDITOR.instances.editor1.getData(); 
                        var orig=ace_session.getValue();// editAreaLoader.getValue('txtarea1');//$("#txtarea1").val();
                        // alert(orig);
                        var newcont=tab_content[x];
                        //$("#txtarea1").val(insert_body_contents(orig,newcont));
                    
                        //editAreaLoader.setValue('txtarea1',insert_body_contents(orig,newcont)); 
                        ace_session.setValue(insert_body_contents(orig,newcont));
                        //alert("into text"+tab_content[x]);
                  
                        showtextarea();
              
                    }
            
                }
        
        
            }
    

            function button_disabler()
            {
                if(guitemp==true)
                {
        
                    document.getElementById("gui"+selected_file+"").disabled=true; 
                    document.getElementById("text"+selected_file+"").disabled=false;
                }
                if(guitemp==false)
                {document.getElementById("gui"+selected_file+"").disabled=false; 
                    document.getElementById("text"+selected_file+"").disabled=true;
                }
    
            }



            //-----------------------------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------------------------

            function check_if_view(path)
            {
                var i="";
                path=path.toString();
                var tab=new Array();
                tab=path.split('/');
        
                i=tab.length
                i=i-3;
        
                if(tab[i]=="view")
                {
                    return(true);
                }
                else
                {
                    return(false);
            
                }
        
                //alert("view");
        
            }

    



            //-------------------------------------------------------------------------------------------------------









            function open_event_handler()
            {     var path=selected_file;
                var path=path.replace("view","event_handler");
           
                //alert(path);
        
      
                $.get("server/get_file_contents.php",{filename:path,id:id},function(data){
                    //alert(data);
               if(original_event_file_name.length<=0)
                    {
                      event_checker=0;
                      
                    }
                    else
                        {
                 for(x in original_event_file_name)
                       {
                           
                       if(path==original_event_file_name[x]) 
                           {
                             event_checker=1;  
                             break;
                               
                           }
                           else
                               {
                                 event_checker=0;  
                                   
                               }
                      
                       }
                        }
                       check_ev(path,data);
                    register_new_file();
                    check_event_tab(path,data);
                    txtarea_to_var();	
     
	
                });
    
    
   
    
            }
            
            
            
            function check_ev(path,data)
            {
                
                
                    if(event_checker==0)
                    {
                  original_event_file_name.push(path);
                    original_event_file_data.push(data);
                    }
                    else
                        {
                          //alert("exist");  
                        }
            }
            
            
            
        
   
            function check_event_tab(path,data)
            { var tabber="";
                for(x in tab_name)
                {
                    if(tab_name[x]==path)
                    {
                        tabber=true;
                        break;
                    }
                    else
                    {
                        tabber=false;
                        
                    }
                
                }
                if(tabber==false)
                {
                    create_event_tab(path,data); 
                 
                }
                else
                {
                    show_tab(path);
                    
                }
   
            }
            
            
            
            
            function create_event_tab(path,data)
            {
                
                original_tab_content.push(data);
                var id=path;

                var newtd=document.createElement("td");								//create new  tablebox
                document.getElementById("tabs_container_table").appendChild(newtd);
                newtd.className="tab_td";
                newtd.id="new"+path+"";
       
                tab_disp_name(path);
                        
        
        
                document.getElementById("closediv"+path+"").onmouseover=function(){document.getElementById("closediv"+path+"").src="images/close_button_over.png";};
        
        
        
        
       
                document.getElementById("closediv"+path+"").onmouseout=function(){document.getElementById("closediv"+path+"").src="images/close_button.png";};
        
                document.getElementById("closediv"+path+"").onmousedown=function(){/*blur()*/;keep_in_textarea();check_save(path);	};
                document.getElementById("name"+path+"").onmousedown=function(){keep_in_textarea();show_tab(path);};
    
                tab_name.push(path);
                tab_content.push(data);
                //alert(tab_name);
            
                color_view_after_event_tab_created(path);    
            }




        
            function color_view_after_event_tab_created(path)
            {
                var path=path.replace("event_handler","view");
                //alert("color changed");
                color_tab(path);
                document.getElementById("text"+path+"").disabled=true;
            }


















            //-----------------------------------------------------------------------------------------------------------------------------------
    
            //-----------------------------------------------------------------------------------------------------------------------------------
            var event_open_flag="";
            function get_event_handler(id_val,action_val)
            {
                // alert(selected_file);
                for(x in tab_name)
                {
            
                    if(tab_name[x]==selected_file)
                    {
                           
                        tab_content[x]=CKEDITOR.instances.editor1.getData(); 
                        var orig= ace_session.getValue();//editAreaLoader.getValue('txtarea1');//$("#txtarea1").val();
                        // console.log(orig);
                     
                        // alert(orig);
                        var newcont=tab_content[x];
                        //console.log(newcont);
                        tab_content[x]=insert_body_contents(orig,newcont);
                        //$("#txtarea1").val(tab_content[x]);
                        //editAreaLoader.setValue('txtarea1',tab_content[x]);
                        ace_session.setValue(tab_content[x]);
                        break;
                    }
					
					
                }
                //alert(selected_file);
        
     
                var path=selected_file.replace("view","event_handler");
                //alert(path);
      
      
   
      
      
      
      
      
      
      
      
      
                selected_file=path;
                //alert(path);
             
                //alert(id_val+action_val);
                var event=id_val+"__"+action_val+"()";
   
   
   
   //browse to find original event file
   for(x in original_event_file_name)
       {
           if(original_event_file_name[x]==selected_file)
               {
                   
                   original_event_file=original_event_file_data[x];
                   break;
               }
           
           
       }
   
   
   
   
   
   
   
            
                for(x in tab_name)
                {
                    if(tab_name[x]==path)
                    {
                        event_open_flag=true;
                        break;
                    }
			
			
                }
			
			
                if(event_open_flag==true)
                {
                    eventor(event,path);
                    show_tab(path);
                }
                else
                {
                    alert("please open event handler file");
			
                }  
				
				
				
				
				
				
				
                
         
            
          
                function eventor(event,path)
                {
                    if(check_event_exists(original_event_file,event)==true)
                    {
                        alert("event exists");
                        new_data=original_event_file;
                        //for(x in tab_name)
                        //{ if(tab_name[x]==path)
                        // {      
                        
                        //tab_content[x]=new_data;
                        //break;
                        // }
                            
                        // }
           
                    }
                    if(check_event_exists(original_event_file,event)==false)
                    {
                        //alert("new event");
                        var ins_co="public function "+event+"\n{ \n\n }";
                        var new_data=insert_event_method(original_event_file,ins_co);
                        for(x in tab_name)
                        { if(tab_name[x]==path)
                            {      
                            
                                tab_content[x]=new_data;
                                original_event_file=tab_content[x];
                                break;
                            }
                        }
                    
                    }
        
                }
             

            }
    
    
    
    
    
    
    
    
    
    
    
  
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
            //-----------------------------------------------------------------------------------------------------------------------------------
    
            //-----------------------------------------------------------------------------------------------------------------------------------
    
            //-----------------------------------------------------------------------------------------------------------------------------------
    
            //-----------------------------------------------------------------------------------------------------------------------------------
    





            //---------------------------------------------------------------------------------------------------
            //---------------------------------------------------------------------------------------------------


       

            function get_explorer_files(){

                var explr_dir=$('#exploredir').val();
                $.get("server/get_explorer_files.php",
                {project:'<?php echo $_GET['project']; ?>',path:explr_dir},
                function(data){
        
                    len=data.length;
                    var i=0;
                    var str="";
                    var str2=""
            
                    for(i=0;i<data.length;i++){
                
                        if(data[i]['type']=='dir'){
                            str+="<div class='explr_file' ><img src='images/folderimage.png' style='height:25px;width:25px' /> <span onclick='browse_dir(\""+data[i]['name']+"\")'>"+data[i]['name']+"</span><span  onclick='show_option(\""+data[i]['name']+"\",\"dir\")' style='float:right' onclick=''><img src='images/option.png' height=24 width=24 /></span></div>";
                        }
                        else{
                            str2+="<div class='explr_file'><img src='images/fileimage.png' style='height:25px;width:25px' />"+data[i]['name']+"<span style='float:right' onclick='show_option(\""+data[i]['name']+"\",\"file\")'><img src='images/option.png' height=24 width=24 /></span></div>";                    
                        }
                    }
            
                    $('#explr_list').html(str+str2);
                },'json');


            }


            function upload_file(){
        
                var base=$('#exploredir').val();
                window.open('server/upload.php?project='+radt_project_name+'&base='+base,'_newtab','height=200,width=300');
        
            }

            function show_option(name,type){
                var cdir=$('#exploredir').val();
                if(cdir==""){
               
                }
                else{
                    cdir+="/";
                }
                var filename="../projects/"+radt_project_name+"/"+cdir+name;
                window.open('server/f_option.php?filename='+filename+'&type='+type,'_newtab');
            }
            function browse_dir(dir){

                var explr_dir=$('#exploredir').val();
        
                if(explr_dir==""){
                    //explr_dir+="/";            
                }
                else if(explr_dir[explr_dir.length-1]=="/"){
            
                }
                else{
                    explr_dir+="/";
                }
                $('#exploredir').val(explr_dir+dir);
                get_explorer_files();

            }

            function browse_up(){
    
                var explr_dir=$('#exploredir').val();
            
                //nothing has to be done
                if(explr_dir=="")
                {
                    return;
                }
         

                if(explr_dir.indexOf('/')>0){
                    /*omit the last dir name
                     * if input is abc/def/ghi
                     * we split it into array: abc,def,ghi
                     * then the last element is omitted : abc,def
                     * they are combined again: abc/def
                     */
                    var aray=explr_dir.split('/');
                    aray.pop();
                    explr_dir=aray.join('/');
            
                }
                else{
                    explr_dir="";
                }
    
                //Set the PATH in the input box.
                $('#exploredir').val(explr_dir);
    
    
                //reload all the files from the server by referring the set PATH.
                get_explorer_files();
    
            }


            $(document).ready(function(){
                browse_packs();
                get_explorer_files();
            });

            /*
             * Saves the contents of textarea.
             */
            function save_file(){
  
                for(x in tab_name)
                {
                    if(selected_file==tab_name[x])
                    {
                        if(guitemp==true)
                        {    
                            tab_content[x]=CKEDITOR.instances.editor1.getData(); 
                            var orig=ace_session.getValue();//editAreaLoader.getValue('txtarea1'); //$('#txtarea1').val();
                            var newcont=tab_content[x];
                            var contents= insert_body_contents(orig,newcont);
                  
          
                        }
                        else
                        {
                            tab_content[x]=ace_session.getValue(); //editAreaLoader.getValue('txtarea1'); //$('#txtarea1').val();
                            var contents=tab_content[x];
                        }
            
                    }
                }
                $.post("server/save_file_contents.php",{file:selected_file,contents:contents},function(data){
       
                    alert(data);   
                });  
   
                //part of the tabs code while saving tabs-----------------------------------------------------
                for(x in tab_name)
                {
                    if(selected_file==tab_name[x])
                    {
                        tab_content[x]=contents;
                        //$('#txtarea1').val(contents);
                        //editAreaLoader.setValue('txtarea1',contents);
                        ace_session.setValue(contents);
                    }
                }//---------------------------------------------------------------------------------------
            }

            function browse_packs()
            {
                var current_dir=$("#currentdir").val();
                var project='<?php echo $_GET['project']; ?>';
                $.get("server/get_packs_folders.php",{current_dir:current_dir,project_dir:project},function(data){
        
                    var len=data.length;
                    var i=0;
                    var str1="";
                    var str2="";
                
                    my_current_dir="";
                    if(current_dir==""){
                    
                 
                    }else{
                    
                        my_current_dir=current_dir+"/";
                    }
                    for(i=0;i<len;i++)
                    {
                        if(data[i]['type']=='file'){
                            str1 +="<div class='packs_div'> <img src=\"images/packimage.png\" height=\"25px\" width=\"auto\" /><span  onmousedown='display_pack_files(\""+data[i]['name']+"\")'> "+data[i]['name']+"</span><span style='float:right' onclick='delete_package(\""+data[i]['name']+"\")'><img src='images/editor_delete_button.png' height='20' width='20' title='Delete'/></span><a style='float:right' href='projects/"+radt_project_name+"/"+my_current_dir+data[i]['name']+"' target='_blank' ><img src='images/play_button.png' height='20' width='20' title='Run'/></a></div>";
                        }
                        else if(data[i]['type']=='dir'){
                            str2 +="<div class='packs_div'><img src=\"images/folderimage.png\" height=\"25px\" width=\"auto\" /><span  onclick='browse_pack_folder(\""+data[i]['path']+"\")'> "+data[i]['name']+"</span><span style='float:right' onclick='delete_folder(\""+data[i]['path']+"\")'><img src='images/editor_delete_button.png' height='20' width='20' title='Delete'/></span></div>";
                        }
                    }
            
                    $('#pack_list').html(str2+str1);
                    $('#files').html("");
        
                },'json');
    
    
    
            }


            function browse_pack_folder(path)
            {
                $("#currentdir").val(path);
                browse_packs();
            }

            function  browse_packs_back(){
    
                var explr_dir=$('#currentdir').val();
            
                //nothing has to be done
                if(explr_dir=="")
                {
                    return;
                }
         

                if(explr_dir.indexOf('/')>0){
                    /*omit the last dir name
                     * if input is abc/def/ghi
                     * we split it into array: abc,def,ghi
                     * then the last element is omitted : abc,def
                     * they are combined again: abc/def
                     */
                    var aray=explr_dir.split('/');
                    aray.pop();
                    explr_dir=aray.join('/');
            
                }
                else{
                    explr_dir="";
                }
                $('#currentdir').val(explr_dir);
                browse_packs();

    
    
            }


            function create_package()
            {
                var strpack;
                strpack=$("#pack_name").val();
                var cdir=$('#currentdir').val();
    
                $.get("server/create_package.php",{packname:strpack,project_name:'<?php echo $_GET['project'] ?>',current_dir:cdir},function(data){
                    alert(data);
                    browse_packs();
                    $("#pack_name").val('');
        
                });
            }
        
            function create_folder()
            {
                var strpack;
                strpack=$("#pack_name").val();
                var cdir=$('#currentdir').val();
    
                $.get("server/create_folder.php",{foldername:strpack,project_name:'<?php echo $_GET['project'] ?>',current_dir:cdir},function(data){
                    alert(data);
                    browse_packs();
                    $("#pack_name").val('');
        
                });
            }
        

    </script>

    <script>
            function insert_event_method(orig,ins_code){
            
                len=orig.length;
                var k=0;
                for(k=len-1;k!=0;k--){
               
                    if(orig[k]=='}'){
                        break;
                    }
                }
           
           
                orig=orig.substring(0,k);
           
                orig=orig+"\n"+ins_code+"\n}";
                console.log(orig);
                return(orig);
            
            }
            
            function check_event_exists(orig,event_name){
            
            
                if(orig.search(event_name)>=0)
                {
    
                    return true;
                }            
                return false;
            }
                    
                    
    </script>





    <?php
    require "footer.php";
    ?>
